import React, { CSSProperties, useEffect, useMemo, useRef, useState } from 'react';
import "./EditPage.scss";
import TopicSiderBar from '../office-lib/topic-sider-bar/TopicSiderBar';
import TopicSiderBarV2 from '../office-lib/topic-sider-bar/TopicSiderBarV2';
import { OptionBarActionType, TypeEditorColor, TypeEditorNav, TypeExcelConfig, TypeInlineStyleDict, TableDataCell } from '../../types';
import { ContentBlock } from 'draft-js';
import EditorPageNav from '../office-lib/editor-page-nav/EditorPageNav';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import EditPageLoading from './EditPageLoading';
import systemApi from '../../api/system';
import {
    CellStyleConfig,
    DocConfig,
    DocConfigBaseInfo,
    DocOptionHistory,
    DocInstance,
    ExcelFormatBrush,
    LuckySheetSelectionRange,
    TopicType,
    PlanningBasisType,
    EditPageNavType
} from '../../utils/types';
import "./EditPage.scss";
import DocContextProvider from '../../context/DocContext';
import DocEditorContext from './../../context/DocEditorContext';
import EditorOptionBarForExcel from '../office-lib/excel-editor-option-bar/EditorOptionBarForExcel';
import EditorOptionBarForWord from '../office-lib/word-editor-option-bar/EditorOptionBarForWord';
import WordEditorV2 from '../office-lib/word-editor-deprecated/WordEditorV2';
import {
    deepCloneV2,
    defaultDocConfig,
    defaultExcelCellStyleConfig,
    defaultExcelFormatBrushConfig,
    isEmpty
} from '../../utils';
import WordEditorPluginsTabs from '../office-lib/word-editor-plugins/WordEditorPluginsTabs';
import ExcelEditorV2 from '../office-lib/excel-editor/ExcelEditorV2';
import WordEditorV3 from '../office-lib/word-editor/WordEditorV3';
import { generateDocInstance } from '../office-lib/word-editor/editor-doc-item-generate';
import DocEditorProvider from '../../context/DocEditorProvider';
import { DocItem } from '../slate-editor';
import { saasConfig } from '../../config/theme-config';
import TopicManagePage from '../office-lib/topic-manage-page/TopicManagePageV2';
import useReSize from '../../hooks/useResize';

const EditPage = () => {
    const navigate = useNavigate();
    const [searchParams, setSearchParams] = useSearchParams();

    const [pageLoading, setPageLoading] = useState(true);

    const delayTimer = useRef<any>(null);
    const delayTimer1 = useRef<any>(null);
    const wordEditorRef = useRef<any>(null);
    const excelEditorRef = useRef<any>(null);
    const editorPageNavRef = useRef<any>(null);
    const wordRecommandSiderRef = useRef<any>(null);
    const wordEditorOptionBarRef = useRef<any>(null);
    const excelEditorOptionBarRef = useRef<any>(null);
    const editPageContentBodyRef = useRef<any>(null);
    const topicSideBarContainerRef = useRef<any>(null);

    const comDocInstanceChangeTimeoutRef = useRef<any>(null);

    //当前的规划实例
    const [comDocInstance, setComDocInstance] = useState<DocInstance>(null);
    //当前的规划配置
    const [comDocConfig, setComDocConfig] = useState<DocConfig>(defaultDocConfig)
    const [comFocusTopicNode, setcomFocusTopicNode] = useState<TopicType>(null);
    const [comFocusTableCellList, setComFocusTableCellList] = useState<TableDataCell[]>(null);
    const [comCellStyleConfig, setComCellStyleConfig] = useState<CellStyleConfig>({});

    const [currentFocusedDocItem, setCurrentFocusedDocItem] = useState<DocItem>(null);

    const [currentComExcelSelectionRange, setCurrentComExcelSelectionRange] = useState<LuckySheetSelectionRange>({
        column: [0, 12],
        row: [0, 0]
    });

    const [currentComExcelFormatBrushConfig, setCurrentComExcelFormatBrushConfig] = useState<ExcelFormatBrush>(defaultExcelFormatBrushConfig);

    const editPageTopicPageRef = useRef<any>(null);
    const editPageExcelRef = useRef<any>(null);
    const editPageWordRef = useRef<any>(null);

    const pageContainerEl = useRef<any>(null);

    const [comFocusLayoutTopicNode, setComFocusLayoutTopicNode] = useState(null);

    useEffect(() => {
        const handleBeforeUnload = (e) => {
            e.preventDefault();
            e.returnValue = '';
            return '确认离开此规划编制页面吗？请确保所有修改已保存';
        };
        window.addEventListener('beforeunload', handleBeforeUnload);
        return () => {
            window.removeEventListener('beforeunload', handleBeforeUnload);
        };
    }, []);

    useEffect(() => {
        //@ts-ignore
        const currenPagetNavType: EditPageNavType = searchParams.get("screen");
        toggleEditPageLayoutVisible(currenPagetNavType);
    }, [searchParams]);



    useEffect(() => {
        queryProjectDetails();
        setComCellStyleConfig(deepCloneV2(defaultExcelCellStyleConfig));
        return () => {
            delayTimer.current && clearTimeout(delayTimer.current);
            delayTimer1.current && clearTimeout(delayTimer1.current);
            comDocInstanceChangeTimeoutRef.current && clearTimeout(comDocInstanceChangeTimeoutRef.current)
        }
    }, [])

    const checkPlanBasisProtectlandType = (docInstance: DocInstance, protectlandTypeStr: string, planBasisProvince: string): boolean => {
        let isInclude = false;
        const {
            protectland: {
                subType,
                subTypeStr,

            },
            protectlandProvince
        } = docInstance;
        const protectlandType = subTypeStr.substring(0, subTypeStr.length - subType.length);
        const protectlandSubType = subType;
        let planBasisProtectlandGroupList = protectlandTypeStr.split(',');
        planBasisProtectlandGroupList.forEach(ele => {
            let planBasisProtectlandType = ele.split('/')[0];
            let planBasisProtectlandSubType = ele.split('/')[1] ? ele.split('/')[1] : '';
            if (planBasisProtectlandType == protectlandType) {
                //如果没有
                if (isEmpty(planBasisProtectlandSubType)) {
                    isInclude = true;
                } else if (planBasisProtectlandSubType == protectlandSubType) {
                    isInclude = true;
                }
            }
        })
        if (planBasisProvince.indexOf(protectlandProvince) == -1 && planBasisProvince !== '全选') {
            isInclude = false;
        }
        return isInclude;
    }

    const queryProjectDetails = () => {
        let params = {
            id: searchParams.get("docId")
        }
        let pageParams = {
            page: 1,
            size: 9999,
        }
        Promise.all([
            systemApi.getProjectBaseInfo(params),
            systemApi.queryDocExtraConfigInfo(params),
            systemApi.getPanningBasisList(pageParams)
        ])
            .then(resList => {
                //@ts-ignore
                let tempComDocConfig: DocConfig = resList[1].data;
                let tempComDocInstance: DocInstance = resList[0].data;
                const planBasisList: PlanningBasisType[] = resList[2].data.list.filter(ele => {
                    return checkPlanBasisProtectlandType(tempComDocInstance, ele.protectlandType, ele.province)
                });
                let {
                    generatedDocConfig,
                    generatedDocInstance
                } = generateDocInstance(
                    resList[0].data,
                    tempComDocConfig,
                    planBasisList
                );
                if (generatedDocInstance) {
                    generatedDocInstance.updateComponentName = 'EditPageContainer';
                    document.title = generatedDocInstance.name + " | 自然保护地规划智慧辅助系统";
                    setComDocConfig(generatedDocConfig);
                    handleSetcomDocInstance(generatedDocInstance);
                    delayTimer.current = setTimeout(() => {
                        setPageLoading(false);
                        //@ts-ignore
                        const currentScreen: EditPageNavType = searchParams.get("screen");
                        toggleEditPageLayoutVisible(currentScreen);
                        editorPageNavRef.current?.handleSetDefaultActiveNavType(currentScreen);
                    }, 200);
                }
            })
            .catch(err => {
                console.log("err", err)
            })
    }

    /**
     * 
     * @param layoutVisible 是否展示word
     * @returns 
     */
    const toggleEditPageLayoutVisible = (activeNavType: EditPageNavType) => {
        try {
            if (!wordEditorRef.current || !wordRecommandSiderRef.current) {
                return;
            }
            editorPageNavRef.current.handleSetDefaultActiveNavType(activeNavType)
            switch (activeNavType) {
                case 'topic':
                    editPageTopicPageRef.current.style.display = `flex`;
                    editPageExcelRef.current.style.display = `none`;
                    editPageWordRef.current.style.display = `none`
                    break;
                case 'excel':
                    editPageTopicPageRef.current.style.display = `none`;
                    editPageExcelRef.current.style.display = `flex`;
                    editPageWordRef.current.style.display = `none`
                    break;
                case 'word':
                    editPageTopicPageRef.current.style.display = `none`;
                    editPageExcelRef.current.style.display = `none`;
                    editPageWordRef.current.style.display = `flex`
                    break;
                default:
                    break;
            }
            if (activeNavType == 'topic') {
                topicSideBarContainerRef.current.style = "display: none";
            } else {
                topicSideBarContainerRef.current.style = "display: flex";
            }
            wordEditorOptionBarRef.current?.toggleLayoutVisible(activeNavType === 'word');
            excelEditorOptionBarRef.current?.toggleLayoutVisible(activeNavType === 'excel');
        } catch (e) {
            console.log("toggleEditPageLayoutVisible---err", e)
        }
    }

    const _onHandleResize = (newLayoutWidth: number) => {
        editPageContentBodyRef.current.style.width = `calc(100% - ${8 + newLayoutWidth}px)`;
        excelEditorRef.current?.handleChangeMainResize(newLayoutWidth);
    }

    const onEditorNavChange = (editorNavType: EditPageNavType) => {
        switch (editorNavType) {
            case 'topic':
                setSearchParams({ docId: searchParams.get("docId"), screen: 'topic', sidetab: searchParams.get("sidetab") || 'allTopic' });
                break;
            case 'excel':
                setSearchParams({ docId: searchParams.get("docId"), screen: 'excel', sidetab: searchParams.get("sidetab") || 'allTopic' });
                break;
            case 'word':
                setSearchParams({ docId: searchParams.get("docId"), screen: 'word', sidetab: searchParams.get("sidetab") || 'allTopic' });
                break;
            default:
                break;
        }
    }

    const onNavigateBack = () => {
        const formPath = localStorage.getItem('formEditPagePath')
        if (formPath) {
            navigate(formPath)
        } else {
            navigate('/home')
        }
    }

    const _handleSetcomDocInstance = (newComDocInstance: DocInstance) => {
        console.log("=========editPage更新comDocInstance======")
        setComDocInstance(deepCloneV2(newComDocInstance));
    }

    const handleSetcomDocInstance = (newComDocInstance: DocInstance) => {
        console.log("handleSetcomDocInstance--->", newComDocInstance)
        setComDocInstance(newComDocInstance);
    }

    const handleSetcomDocConfig = (newcomDocConfig: DocConfig) => {
        setComDocConfig(newcomDocConfig);
    }

    const handleContextMenu = (event: any) => {
        event.preventDefault();
    }

    const handleSetcomFocusTopicNode = (topicNode: TopicType) => {
        setcomFocusTopicNode(topicNode)
    }

    const handleSetComFocusTableCellList = (tableDataCellList: TableDataCell[]) => {
        setComFocusTableCellList(tableDataCellList);
    }

    const handleSetComCellStyleConfig = (newComCellStyleConfig: CellStyleConfig) => {
        localStorage.setItem('comCellStyleConfig', JSON.stringify(newComCellStyleConfig));
        setComCellStyleConfig(newComCellStyleConfig);
    }

    const renderWordEditor = useMemo(() => () => {
        return (
            <WordEditorV3
                ref={wordEditorRef}
            />
        )
    }, [comDocInstance])

    const renderExcelEditor = useMemo(() => () => {
        return (
            <ExcelEditorV2
                ref={excelEditorRef}
                handleSetFocusTableCellList={_handleSetFocusTableCellList}
            />
        )
    }, [comDocInstance])

    const renderTopicManagePage = useMemo(() => () => {
        return (
            <TopicManagePage />
        )
    }, [comDocInstance]);

    const getExcelExportParams = () => {
        const params = excelEditorRef.current?.getExcelExportParams();
        return params;
    }

    const onDispathCellStyle = (e) => {
        excelEditorRef.current?.onDispathCellStyle(e);
    }

    const onDispathCellBorderStyle = (e) => {
        excelEditorRef.current?.onDispathCellBorderStyle(e);
    }

    const onDispathExcelConfig = (e) => {
        excelEditorRef.current?.onDispathExcelConfig(e);
    }

    const getWordExportParams = () => {
        const params = wordEditorRef.current?.getWordExportParams();
        return params;
    }

    const fillSpeciesInfoList = (e) => {
        wordEditorRef.current?.fillSpeciesInfoList(e);
    };

    const insertDocItemToCursorPosition = (e) => {
        wordEditorRef.current?.insertDocItemToCursorPosition(e)
    }

    const handleInsertDocItemByTargetTopicName = (e) => {
        wordEditorRef.current?.insertDocItemByTargetTopicName(e)
    }

    const handleSetFocusDocItem = (e) => {
        wordEditorRef.current?.handleSetFocusDocItem(e)
    }

    const _handleSetFocusTableCellList = (e) => {
        excelEditorOptionBarRef.current.handleSetFocusTableCellList(e)
    }

    const renderTopicSideBar = useMemo(() => () => {
        return <TopicSiderBarV2
                onHandleResize={_onHandleResize}
            />
        if (saasConfig.systemType == 'QingYuanDefault') {
            return <TopicSiderBarV2
                onHandleResize={_onHandleResize}
            />
        }
        return (
            <TopicSiderBar
                onHandleResize={_onHandleResize}
            />
        )
    }, [])

    const handlePasteCellText = useMemo(() => (newText: string) => {
        const luckSheetInputEl: Element = document.getElementById("luckysheet-input-box");
        const inputStyleStr: string = luckSheetInputEl.getAttribute('style');
        if (inputStyleStr.includes("z-index: 1")) {

        } else {
            excelEditorRef.current?.pasteCellText(newText)
        }
    }, [])

    const handleSetCurrentFocusParagraphBlock = (docItem: DocItem) => {
        setCurrentFocusedDocItem(docItem)
    }

    const handleSetCurrentComExcelSelectionRange = (range: LuckySheetSelectionRange) => {
        setCurrentComExcelSelectionRange(range)
    }

    const handleSetCurrentComExcelFormatBrushConfig = (excelFormatBrush: ExcelFormatBrush) => {
        setCurrentComExcelFormatBrushConfig(excelFormatBrush)
    }

    const handleSetComFocusLayoutTopicNode = (e) => {
        setComFocusLayoutTopicNode(e);
    }

    const changeBackgroundParagraph = (e) => {
        wordEditorRef.current.changeBackgroundParagraph &&
            wordEditorRef.current.changeBackgroundParagraph(e)
    }

    const handleRecommandMainProjectDevice = () => {
        excelEditorRef.current.recommandMainProjectDevice();
    }

    const onMouseDown = (e: any) => {
        e.stopPropagation();
    }

    const _handleClearCellStyle = (e) => {
        excelEditorRef.current.handleClearCellStyle(e);
    }

    const containerSize = useReSize(pageContainerEl);

    useEffect(() => {
        // console.log("containerSize--->", containerSize)
        const { height } = containerSize;
        if (editPageTopicPageRef.current) {
            editPageTopicPageRef.current.style.height = (height - 64) + 'px';
        }
        if (editPageExcelRef.current) {
            editPageExcelRef.current.style.height = (height - 156) + 'px';
        }
        if (editPageWordRef.current) {
            editPageWordRef.current.style.height = (height - 156) + 'px';
        }
        //@ts-ignore
        toggleEditPageLayoutVisible(searchParams.get("screen"))
    }, [containerSize]);

    return (
        <DocContextProvider.Provider
            value={{
                //规划报告实例
                comDocInstance,
                _setComDocInstance: _handleSetcomDocInstance,
                //规划配置
                comDocConfig,
                _setComDocConfig: handleSetcomDocConfig,
                //
                comFocusTopicNode: comFocusTopicNode,
                comFocusTableCellList: comFocusTableCellList,
                _setComFocusTopicNode: handleSetcomFocusTopicNode,
                _setComFocusTableCellList: handleSetComFocusTableCellList,
                //剪切板
                _pasteCellText: handlePasteCellText,
                comCellStyleConfig: comCellStyleConfig,
                _setComCellStyleConfig: handleSetComCellStyleConfig,
                //当前光标段落
                currentFocusedDocItem: currentFocusedDocItem,
                _setCurrentFocusedDocItem: handleSetCurrentFocusParagraphBlock,
                comExcelSelectionRange: currentComExcelSelectionRange,
                _setComExcelSelectionRange: handleSetCurrentComExcelSelectionRange,
                comExcelFormatBrushConfig: currentComExcelFormatBrushConfig,
                _setComExcelFormatBrushConfig: handleSetCurrentComExcelFormatBrushConfig,
                comFocusLayoutTopicNode: comFocusLayoutTopicNode,
                _setComFocusLayoutTopicNode: handleSetComFocusLayoutTopicNode
            }}
        >
            <DocEditorProvider>
                <div
                    id="editPageId"
                    ref={pageContainerEl}
                    className='flex-col edit-page-container-v1'
                    onContextMenu={handleContextMenu}
                >
                    <div style={{ width: '100%', zIndex: 9999 }}>
                        <EditorPageNav
                            ref={editorPageNavRef}
                            onEditorNavChange={onEditorNavChange}
                            onNavigateBack={onNavigateBack}
                        />
                    </div>
                    <EditorOptionBarForExcel
                        ref={excelEditorOptionBarRef}
                        getExcelExportParams={getExcelExportParams}
                        getWordExportParams={getWordExportParams}
                        onDispathCellStyle={onDispathCellStyle}
                        onDispathCellBorderStyle={onDispathCellBorderStyle}
                        onDispathExcelConfig={onDispathExcelConfig}
                        handleRecommandMainProjectDevice={handleRecommandMainProjectDevice}
                        _handleClearCellStyle={_handleClearCellStyle}
                    />
                    <EditorOptionBarForWord
                        ref={wordEditorOptionBarRef}
                        getExcelExportParams={getExcelExportParams}
                        getWordExportParams={getWordExportParams}
                        fillSpeciesInfoList={fillSpeciesInfoList}
                    />
                    {
                        comDocInstance && comDocInstance.topicList && comDocInstance.topicList.length && comDocConfig ?
                            <div
                                className='edit-page-content-v1 flex-row'
                            >
                                <div ref={topicSideBarContainerRef} className='topic-side-bar-container'>
                                    {renderTopicSideBar()}
                                </div>
                                <div
                                    ref={editPageContentBodyRef}
                                    className='edit-page-content-body-v1'
                                    style={{ width: '100%' }}
                                >
                                    <div
                                        ref={editPageTopicPageRef}
                                        className='edit-page-content-wapper-v1'
                                        style={{ height: 'calc(100vh - 64px)' }}
                                    >
                                        {renderTopicManagePage()}
                                    </div>
                                    <div
                                        ref={editPageExcelRef}
                                        className='edit-page-content-wapper-v1'
                                        style={{ height: 'calc(100vh - 156px)'}}
                                    >
                                        {renderExcelEditor()}
                                    </div>
                                    <div
                                        ref={editPageWordRef}
                                        className='flex-row edit-page-content-wapper-v1'
                                        style={{ height: 'calc(100vh - 156px)' }}
                                        onMouseDown={onMouseDown}
                                        onMouseUp={onMouseDown}
                                        onClick={onMouseDown}
                                    >
                                        {renderWordEditor()}
                                        <div
                                            ref={wordRecommandSiderRef}
                                            className='flex-row edit-page-content-right-v1 content-border content-border-radius'
                                            style={{ marginLeft: 10 }}
                                        >
                                            <WordEditorPluginsTabs
                                                changeBackgroundParagraph={changeBackgroundParagraph}
                                                insertDocItemByTargetTopicName={handleInsertDocItemByTargetTopicName}
                                                insertDocItemToCursorPosition={insertDocItemToCursorPosition}
                                                handleSetFocusDocItem={handleSetFocusDocItem}
                                            />
                                        </div>
                                    </div>
                                </div>
                            </div>
                            :
                            <div className='flex-col' style={{ width: '100%', flex: 1, justifyContent: 'center', alignItems: 'center' }}>
                                <h1 style={{ color: '#909399', marginTop: '12vh' }}>规划数据异常</h1>
                            </div>
                    }
                    {
                        pageLoading ?
                            <EditPageLoading />
                            :
                            null
                    }
                </div>
            </DocEditorProvider>
        </DocContextProvider.Provider>
    )
}


export default EditPage;